package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    //减库存，减库存的同时还要对商品的销量做+
    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";
    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                // 准备参数
                Map<String,Object> param = new HashMap<>();
                param.put("id", entry.getKey());
                param.put("num", entry.getValue());
                // 编译statement，namespace.statementId
                sqlSession.update(DEDUCT_STOCK_STATEMENT, param);
            }
            // 刷新
            sqlSession.flushStatements();
        });
    }
}
